from django.contrib.auth import login, logout
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django import http
import re


# 1.注册功能
from django_redis import get_redis_connection

from apps.users.models import User
from utils.response_code import RETCODE


class RegisterView(View):
    # 注册页面显示
    def get(self, request):
        return render(request, 'register.html')

    # 注册功能提交
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        # 是否同意协议
        allow = request.POST.get('allow')
        if not all([username, password, password2, mobile]):
            return http.HttpResponseForbidden("参数不齐！")

        if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')

        if not re.match('^[a-zA-Z0-9]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20个字符的密码')

        if not re.match('^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入手机号')

        if allow != 'on':
            return http.HttpResponseForbidden('请勾选同意')
        # 短信验证码
        sms_code = request.POST.get('sms_code')
        # 从redis里取出短信代码
        sms_client = get_redis_connection('sms_code')
        redis_sms_code = sms_client.get('sms_%s' % mobile)
        # 判空:
        if redis_sms_code is None:
            return http.HttpResponseForbidden('短信验证码失效')
        # 判断对比
        if sms_code != redis_sms_code.decode():
            return http.HttpResponseForbidden('验证码输入错误！')

        # 注册用户－－
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 保持登陆状态
        login(request, user)
        # 跳转到首页　redirect(reverse())
        return redirect(reverse('contents:index'))


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 1.接收参数 : username password 记住登陆
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 2.判空 all() 判正则
        # django认证系统
        # 3.判断用户名或密码是否匹配
        from django.contrib.auth import authenticate
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # 4.保持登陆状态
        login(request, user)
        if remembered == "on":
            request.session.set_expiry(None)
        else:
            # 默认两周
            request.session.set_expiry(0)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)
        # 退出登录，重定向到登录页
        response = redirect(reverse('contents:index'))
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response



